<route lang="json5">
{
  style: {
    navigationBarTitleText: '个人信息',
    navigationStyle: 'custom',
    // #ifdef MP-ALIPAY
    enablePullDownRefresh: false,
    'mp-alipay': {
      allowsBounceVertical: 'NO',
      transparentTitle: 'always',
      titlePenetrate: 'YES',
      defaultTitle: '',
    },
    // #endif
  },
}
</route>
<template>
  <CustomNavbar :title="'图片生成'" />
  <view class="person-msg">
    <scroll-view
      :scroll-top="scrollTop"
      :scroll-y="true"
      class="scroll-Y"
      :refresher-triggered="isTriggered"
    >
      <uni-forms class="form" ref="form" :modelValue="form">
        <Divider margin="5px">对方信息</Divider>
        <uni-forms-item label="对方头像" name="otherAvatar">
          <view class="head" @click="changeAvatar">
            <!-- <image :src="form.avatar || userInfoRef.defaultImage" mode=""></image> -->
            <view>
              <uni-file-picker
                ref="otherAvatarRef"
                :v-model="[{ name: '', extname: '', url: userInfoRef.defaultImage }]"
                limit="1"
                :del-icon="false"
                disable-preview
                :imageStyles="imageStyles"
                file-mediatype="image"
                @select="selectOtherAvatar"
              ></uni-file-picker>
            </view>
          </view>
        </uni-forms-item>
        <uni-forms-item label="对方名称" name="nickname">
          <uni-easyinput type="text" v-model="form.otherName" placeholder="请输入昵称" />
        </uni-forms-item>
        <br />
        <Divider margin="5px">我方信息</Divider>
        <uni-forms-item label="我的头像" name="myAvatar">
          <view class="head" @click="changeAvatar">
            <!-- <image :src="form.avatar || userInfoRef.defaultImage" mode=""></image> -->
            <view>
              <uni-file-picker
                ref="myAvatarRef"
                :v-model="[{ name: '', extname: '', url: userInfoRef.defaultImage }]"
                limit="1"
                :del-icon="false"
                disable-preview
                :imageStyles="imageStyles"
                file-mediatype="image"
                @select="selectMyAvatar"
              ></uni-file-picker>
            </view>
          </view>
        </uni-forms-item>
        <Divider margin="5px">聊天内容</Divider>
        <view class="content-box">
          <view v-for="(content, index) in contentList" :key="index">
            <uni-forms-item :label="content.isMy ? '我方发送' : '对方发送'">
              <view class="master-name">
                <uni-easyinput type="text" v-model="content.content" placeholder="请输入内容" />
                <view class="edit-icon" @tap="delContent(index)">
                  <image src="@/static/global/del.png" mode="" />
                </view>
              </view>
            </uni-forms-item>
          </view>
          <view style="display: flex; justify-content: space-between; margin-bottom: 20rpx">
            <button
              class="mini-btn"
              size="mini"
              @tap="addContent(false)"
              :disabled="form.contentList.length >= 5"
            >
              {{ '添加对方记录' }}
            </button>
            <button
              class="mini-btn"
              size="mini"
              @tap="addContent(true)"
              :disabled="form.contentList.length >= 5"
            >
              {{ '添加我方记录' }}
            </button>
          </view>
        </view>
      </uni-forms>

      <div class="bottom">
        <view class="submit" @click="submit">生成聊天图片</view>
        <view class="submit quiteLoginOut" @click="cancel">返回</view>
      </div>
      <view style="margin-top: 30rpx">浏览效果：</view>
      <image
        style="width: 700rpx; height: 525rpx; margin: 30rpx 20rpx; border: 1px solid #c5c5c5"
        :src="result"
        @click="seeImg"
      ></image>
      <div style="width: 100rpx; height: 300rpx"></div>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import CustomNavbar from '@/components/CustomNavbar.vue'
import Divider from '@/components/o-divider.vue'
import { useUserStore } from '@/store/user'
import { updateUserInfoApi } from '@/service/user'
import { SearchTypeEnum } from '@/enums/SearchTypeEnum'
import { getEnvBaseUrl } from '@/utils'
import { TalkRecord, Content } from '@/types/talkRecord'
import { generateTalkRecordApi } from '@/service/global'

const scrollTop = ref(0)
const isTriggered = ref(false)
const userInfoRef = useUserStore()
const form = {
  id: undefined,
  userId: userInfoRef.userInfo.id,
  otherAvatar: '',
  otherName: '',
  myAvatar: '',
  contentList: [],
}
const contentList = ref<Content[]>([
  { isMy: false, content: '' },
  { isMy: true, content: '' },
])
const otherAvatarRef = ref()
const myAvatarRef = ref()
const baseUrl = getEnvBaseUrl()
const result = ref<string>('')

onLoad(async () => {})
const changeAvatar = () => {}
const selectOtherAvatar = (ev) => {
  form.otherAvatar = ev.tempFiles[0].image.location
}
const selectMyAvatar = (ev) => {
  form.myAvatar = ev.tempFiles[0].image.location
}
const addContent = (isMy) => {
  if (contentList.value.length > 10) {
    uni.showToast({ title: '最多添加11条对话', icon: 'none' })
    return
  }
  contentList.value.push({ isMy, content: '' })
}
const delContent = (index) => {
  contentList.value.splice(index, 1)
}
const seeImg = () => {
  uni.previewImage({
    urls: [result.value], // 需要预览的图片链接列表
    success: () => {
      // 在预览界面用户可以长按保存
    },
    fail: (err) => {
      console.error(err)
    },
  })
}

const submit = async () => {
  console.log('form', form)
  if (!checkReq()) return
  form.userId = userInfoRef.userInfo.id
  // uni.showLoading({ title: '提交中...' })
  // 上传对方头像
  const upOtherAvatarRes = await uni.uploadFile({
    url: baseUrl + '/file/upload',
    filePath: form.otherAvatar,
    name: 'file',
    formData: {
      type: SearchTypeEnum.TALK_RECORD,
      param: JSON.stringify(form),
    },
  })
  // 上传我的头像
  const upOtherAvatarResData = JSON.parse(upOtherAvatarRes.data)
  form.id = upOtherAvatarResData.data.id
  const upMyAvatarRes = await uni.uploadFile({
    url: baseUrl + '/file/upload',
    filePath: form.myAvatar,
    name: 'file',
    formData: {
      type: SearchTypeEnum.TALK_RECORD,
      param: JSON.stringify(form),
    },
  })
  const upMyAvatarResData = JSON.parse(upMyAvatarRes.data)
  console.log(upMyAvatarResData.data)
  // 生成图片
  upMyAvatarResData.data.contentList = contentList.value
  const resultRes = await generateTalkRecordApi(upMyAvatarResData.data)
  console.log('resultRes', resultRes)
  result.value = resultRes.data.resultUrl
  // uni.hideLoading()
  // uni.navigateBack()
  // uni.showToast({ icon: 'none', title: '修改成功' })
}
const checkReq = () => {
  if (!form.otherAvatar || form.otherAvatar === '') {
    uni.showToast({ title: '对方头像为空', icon: 'none' })
    return false
  }
  if (!form.myAvatar || form.myAvatar === '') {
    uni.showToast({ title: '我方头像为空', icon: 'none' })
    return false
  }
  if (!form.otherName || form.otherName === '') {
    uni.showToast({ title: '对方名称为空', icon: 'none' })
    return false
  }

  let contentIsNull = true
  for (const element of contentList.value) {
    if (element.content && element.content !== '') contentIsNull = false
  }
  if (!contentList.value || contentList.value.length === 0 || contentIsNull) {
    uni.showToast({ title: '内容为空', icon: 'none', mask: true })
    return false
  }
  return true
}
const cancel = () => {
  uni.navigateBack()
}

const imageStyles = {
  width: 72,
  height: 72,
  border: {
    radius: '50%',
  },
}

// 获取屏幕安全区域
const { safeAreaInsets } = uni.getSystemInfoSync()
console.log(safeAreaInsets)
</script>

<style lang="scss">
.head {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #909399;
}

.uni-forms {
  align-items: center;
  padding: 0;
  margin-top: 10rpx;
  text-align: center;
  background-color: #ffffff;

  .uni-forms-item {
    height: 110rpx;
    padding: 0 20rpx;
    line-height: 110rpx;
  }
}

.bottom {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  margin-top: 40rpx;
  > .submit {
    width: 40%;
    height: 100rpx;
    line-height: 100rpx;
    color: #fff;
    text-align: center;
    background-color: $main-color;
  }
}

.radio {
  margin-right: 50rpx;
}

.quiteLoginOut {
  background-color: $font-color-base !important;
  // color: #ff6b35 !important;
}
.content-box {
  align-items: center;
  width: 90%;
  padding: 20rpx;
  margin-top: 20rpx;
  margin-left: 2%;
  text-align: center;
  border: 1px solid #c5c5c5;
}
.master-name {
  display: flex;
  flex-direction: row;
  justify-content: start;
}
.edit-icon {
  height: 80rpx;
  margin-left: 10rpx;
  line-height: 80rpx;
  image {
    width: 50rpx;
    height: 50rpx;
  }
}

.scroll-Y {
  width: 100%;
  height: calc(100vh - var(--window-top));
}
</style>
